package com.axend.aerosense.home.fragment;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.ConsoleMessage;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.widget.NestedScrollView;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.axend.aerosense.base.fragment.MvvmBaseFragment;
import com.axend.aerosense.base.impl.ILoadDataResult;
import com.axend.aerosense.base.impl.ILoginStatusChanged;
import com.axend.aerosense.base.livedatabus.LiveDatabus;
import com.axend.aerosense.base.utils.SystemUtil;
import com.axend.aerosense.base.viewmodel.BaseViewModelFactroy;
import com.axend.aerosense.common.adapter.CommonBindingAdapters;
import com.axend.aerosense.common.adapter.ProviderMultiAdapter;
import com.axend.aerosense.common.bean.AlarmBean;
import com.axend.aerosense.common.bean.EarlyWarningBean;
import com.axend.aerosense.common.bean.HomeReportBean;
import com.axend.aerosense.common.config.Gobal;
import com.axend.aerosense.common.router.RouterActivityPath;
import com.axend.aerosense.common.router.RouterFragmentPath;
import com.axend.aerosense.common.services.ILoginService;
import com.axend.aerosense.common.services.config.ServicesConfig;
import com.axend.aerosense.common.ui.CustomUserSelectPopupWindow;
import com.axend.aerosense.common.ui.WebActivity;
import com.axend.aerosense.common.util.ClickUtils;
import com.axend.aerosense.common.util.JsonUtil;
import com.axend.aerosense.home.BuildConfig;
import com.axend.aerosense.home.LogDetailActivity;
import com.axend.aerosense.home.R;
import com.axend.aerosense.home.databinding.HomeFragmentMainBinding;
import com.axend.aerosense.home.entity.HomeBean;
import com.axend.aerosense.home.entity.HomeReportWebBean;
import com.axend.aerosense.home.entity.ReportTypeEnum;
import com.axend.aerosense.home.entity.WardReportBean;
import com.axend.aerosense.home.viewmodel.HomeViewModel;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.gyf.immersionbar.ImmersionBar;
import com.just.agentweb.AgentWeb;
import com.just.agentweb.AgentWebConfig;
import com.just.agentweb.WebChromeClient;
import com.just.agentweb.WebViewClient;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * 首页
 *
 * @date :2020/12/18 11:07
 */

@Route(path = RouterFragmentPath.Home.PAGE_MAIN_HOME)
public class HomeFragment extends MvvmBaseFragment<HomeFragmentMainBinding, HomeViewModel>
        implements ILoginStatusChanged, ILoadDataResult<HomeBean> {

    /** 本地网页文件地址 */
    private static final String HTML_PAGER_PATH = "file:///android_asset/EchartsHome/Ecarts_home.html";
//    private static final String HTML_PAGER_PATH = "file:///android_asset/EchartsHome/Test.html";

    @Autowired(name = ServicesConfig.User.LONGING_SERVICE)
    ILoginService iLoginService;
    private boolean isLoad = true;
    private boolean isCreatView = false;
    private ProviderMultiAdapter alertMultiAdapter, earlyMultiAdapter;
    private boolean isImmersionBarTransparent = true;
    private CustomUserSelectPopupWindow userSelectPopupWindowPopupWindow;
    private AgentWeb agentWeb;
    private WebView webView;
    private WebChromeClient webChromeClient;
    private WebViewClient webViewClient;

    //WebView页面是否加载完成
    private boolean isWebViewPagerLoadFinished = false;
    //WebView的数据是否加载完成
    private boolean isWebViewDataLoadFinished = false;
    //WebView页面数据
    private HomeReportWebBean webViewReportDada;
    private List<WardReportBean> reportList;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ARouter.getInstance().inject(this);
        getPermissions();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        ((AppCompatActivity) getActivity()).setSupportActionBar(viewDataBinding.homeToolbar);
        initSelectPopupWindow();
        init();
    }

    private void init() {
        LiveDatabus.getInstance().with(Gobal.EVENT_KEY.REFESH_HOME ,Integer.class)
                .observe(getViewLifecycleOwner(), bean-> {
                    // 信息变更时重新刷新
                    viewModel.onLoad();
                });
        setLoadSir(viewDataBinding.homeRefreshLayout);
        showLoading();
        viewModel.onLoad();

        /*viewDataBinding.reportMore.setOnClickListener(v->{
            UserInfo userInfo = MmkvHelper.getInstance().getMmkv().decodeParcelable(Gobal.SAVE_KEY.USR_INFO, UserInfo.class);
            //是否跳转到开通vip
            if (userInfo.userVipState == 1){
                ARouter.getInstance().build(RouterActivityPath.Home.PAGE_HOME_WARNING)
                        .withString("roomUuid", "")
                        .withInt("openType", 2)
                        .navigation();
            }else {
                CustomTipsDialog dialog = new CustomTipsDialog(getContext(), getString(R.string.common_vip_service_tips));
                dialog.setPositiveText(R.string.common_to_vip_service);
                dialog.setOnClickBottomListener(new CustomTipsDialog.OnClickBottomListener() {
                    @Override
                    public void onPositiveClick() {
                        dialog.dismiss();
                        ARouter.getInstance().build(RouterActivityPath.Pay.PAGE_PAY_HOME).navigation();
                    }

                    @Override
                    public void onNegtiveClick() {
                        dialog.dismiss();
                    }
                });
                dialog.show();
            }
        });*/

        viewDataBinding.homeWarningMore.setOnClickListener(v -> {
            ARouter.getInstance().build(RouterActivityPath.Home.PAGE_HOME_WARNING)
                    .withString("roomUuid", "")
                    .withInt("openType", 0)
                    .navigation();
        });

        viewDataBinding.homeAdd.setOnClickListener(v -> {
            if (ClickUtils.isFastClick()) return;
            ARouter.getInstance()
                    .build(RouterActivityPath.Dev.PAGE_DEV_HOME)
                    .navigation();
        });

        viewDataBinding.homeDevAddView.setOnClickListener(v -> {
            if (ClickUtils.isFastClick()) return;
            ARouter.getInstance()
                    .build(RouterActivityPath.Dev.PAGE_DEV_HOME)
                    .navigation();
        });

        //切换被监护人
        viewDataBinding.homeUserSwitch.setOnClickListener(v -> {
            //如果滑动之后点击，则先回到顶部，再显示弹窗
            if (viewDataBinding.homeNestedScrollView.getScrollY() > 0) {
                viewDataBinding.homeNestedScrollView.smoothScrollTo(0, 0);
            }
            showSelectPopupWindow();
        });

//        viewDataBinding.homeBannerTop.setIndicatorStyle(IndicatorStyle.DASH)
//                .setLifecycleRegistry(getLifecycle())
//                .setIndicatorHeight(BannerUtils.dp2px(3f))
//                .setIndicatorSliderWidth(BannerUtils.dp2px(3), BannerUtils.dp2px(10))
//                .setAdapter(new BannerAdapter<String>(this, data -> {
//                    Intent intent = new Intent(HomeFragment.this.getActivity(), WebActivity.class);
//                    intent.putExtra(WebActivity.URL, (String) data);
//                    HomeFragment.this.getActivity().startActivity(intent);
//                }))
//                .create();
//        viewDataBinding.homeRefreshLayout.setEnableNestedScroll(true);

        viewDataBinding.homeRefreshLayout.setEnableLoadMore(false);
        viewDataBinding.homeRefreshLayout.requestDisallowInterceptTouchEvent(true);//通知父控件不要拦截事件
        viewDataBinding.homeNestedScrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                Rect scrollBounds = new Rect();
                View firstVisibItem = viewDataBinding.homeCvUserCard;
                firstVisibItem.getGlobalVisibleRect(scrollBounds);

                Rect rect = new Rect();
                viewDataBinding.homeToolbar.getGlobalVisibleRect(rect);

                if (scrollBounds.top >= rect.bottom) {//可见
                    viewDataBinding.homeToolbar.setBackgroundResource(android.R.color.transparent);
                    viewDataBinding.homeTvTitle.setTextColor(getResources().getColor(R.color.white));
                    viewDataBinding.homeAdd.setImageResource(R.drawable.common_user_icon_add);
                    isImmersionBarTransparent = true;

                } else {//完全不可见
                    viewDataBinding.homeToolbar.setBackgroundResource(android.R.color.white);
                    viewDataBinding.homeTvTitle.setTextColor(getResources().getColor(R.color.black));
                    viewDataBinding.homeAdd.setImageResource(R.drawable.common_user_icon_add2);
                    isImmersionBarTransparent = false;
                }
                setImmersionBar(isImmersionBarTransparent);
            }
        });

        viewDataBinding.homeRefreshLayout.setOnRefreshListener(refreshLayout -> {
            viewModel.onLoad();
        });

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        viewDataBinding.homeWarningHistroyRecyclerview.setLayoutManager(linearLayoutManager);
        alertMultiAdapter = new ProviderMultiAdapter();
        viewDataBinding.homeWarningHistroyRecyclerview.setAdapter(alertMultiAdapter);
        alertMultiAdapter.setOnItemClickListener((adapter, view, position) -> {
            AlarmBean alarmBean = (AlarmBean) adapter.getData().get(position);
            Intent intent = new Intent(HomeFragment.this.getActivity(), LogDetailActivity.class);
            intent.putExtra(Gobal.IntentParamType.WARN_OBJECT, alarmBean);
            HomeFragment.this.getActivity().startActivity(intent);
        });

        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        viewDataBinding.homeEarlyRecycleView.setLayoutManager(layoutManager);
        earlyMultiAdapter = new ProviderMultiAdapter();
        viewDataBinding.homeEarlyRecycleView.setAdapter(earlyMultiAdapter);
        earlyMultiAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                EarlyWarningBean earlyWarningBean = (EarlyWarningBean) adapter.getData().get(position);
                Intent intent = new Intent(HomeFragment.this.getActivity(), LogDetailActivity.class);
                intent.putExtra(Gobal.IntentParamType.EARLY_OBJECT, earlyWarningBean);
                HomeFragment.this.getActivity().startActivity(intent);
            }
        });


        viewDataBinding.homeWarningReportMore.setOnClickListener(v -> {
            ARouter.getInstance().build(RouterActivityPath.Home.PAGE_HOME_WARNING)
                    .withString("roomUuid", "")
                    .withInt("openType", 1)
                    .navigation();

        });

        /*viewDataBinding.homeBannerReport.setIndicatorStyle(IndicatorStyle.DASH)
                .setLifecycleRegistry(getLifecycle())
                .setPageStyle(PageStyle.MULTI_PAGE)
                .setPageMargin(BannerUtils.dp2px(10))
                .setIndicatorHeight(BannerUtils.dp2px(3f))
                .setInterval(8000)
                .setIndicatorSliderColor(Color.parseColor("#888888"), Color.parseColor("#3578FC"))
                .setIndicatorView(viewDataBinding.indicatorView)
                .setIndicatorSliderWidth(BannerUtils.dp2px(3), BannerUtils.dp2px(10))
                .setAdapter(new BannerReportAdapter(this, new IReportsClick<WardReportBean>() {
                    @Override
                    public void onAdlReportClick(WardReportBean data) {
                        Intent intent = new Intent(HomeFragment.this.getActivity(), WebActivity.class);
                        intent.putExtra(WebActivity.URL, data.getAdlurl());
                        intent.putExtra(WebActivity.REPORT_KEY, data.getEncrypt());
                        HomeFragment.this.getActivity().startActivity(intent);
                    }

                    @Override
                    public void onSleepReportClick(WardReportBean data) {
                        Intent intent = new Intent(HomeFragment.this.getActivity(), WebActivity.class);
                        intent.putExtra(WebActivity.URL, data.getSleepUrl());
                        intent.putExtra(WebActivity.REPORT_KEY, data.getEncrypt());
                        HomeFragment.this.getActivity().startActivity(intent);
                    }
                }))
                .create();*/

        isCreatView = true;

        createWebView(HTML_PAGER_PATH);
    }

    /** 更新卡片布局中的信息 */
    private void updateCardViewSelected(HomeReportBean reportBean){
        if (null == reportBean) {
            return;
        }

        CommonBindingAdapters.imageCircleHeadUrl(
                viewDataBinding.homeIvUserHeard, reportBean.getWardImg());
        viewDataBinding.homeTvUserName.setText(reportBean.getWardName());
        boolean empty = ObjectUtils.isEmpty(reportBean.getNum());
        viewDataBinding.homeIvReportWarning.setVisibility(empty ? View.VISIBLE : View.GONE);
        viewDataBinding.homeTvReportTips.setVisibility(empty ? View.VISIBLE : View.GONE);
        viewDataBinding.homeLlReportWeb.setVisibility(empty ? View.GONE : View.VISIBLE);
    }

    /** 初始化选择弹出窗 */
    private void initSelectPopupWindow(){
        if (null == userSelectPopupWindowPopupWindow) {
            userSelectPopupWindowPopupWindow = CustomUserSelectPopupWindow.builder(getActivity())
                    .setLayoutRes(R.layout.common_user_select_list)
                    .setHeight(SizeUtils.dp2px(436))
                    .setParentView(viewDataBinding.getRoot())
                    .setSelectedListener(reportBean -> {
                        //选中item的回调
                        updateCardViewSelected(reportBean);

                        isWebViewDataLoadFinished = true;
                        webViewReportDada = new HomeReportWebBean(
                                reportBean.getADLserverIp(),
                                reportBean.getADLserverPort(),
                                SystemUtil.getSystemLanguage(),
                                reportBean.getNum(),
                                reportBean.getReport(),
                                reportBean.getServerPort(),
                                reportBean.getServerIp(),
                                reportBean.getEncrypt()
                        );

                        //webViewReportDada = HomeReportWebBean.test02();
                        //通知webView渲染数据
                        rendererWebViewData();
                    })
                    .build();
        }
    }

    /** 显示选择弹窗 */
    private void showSelectPopupWindow(){
        if (null == userSelectPopupWindowPopupWindow) {
            return;
        }
        userSelectPopupWindowPopupWindow.showAsDropDown(viewDataBinding.homeClUserItem);
    }

    /** 隐藏选择弹窗 */
    private void dismissSelectPopupWindow(){
        if (null == userSelectPopupWindowPopupWindow) { return; }
        userSelectPopupWindowPopupWindow.dismiss();
    }

    /** 更新选择弹出窗口数据 */
    private void updateSelectPopupWindowListData(List<HomeReportBean> reportList){
        if (null == userSelectPopupWindowPopupWindow) {
            return;
        }

        if (ObjectUtils.isEmpty(reportList)) {
            viewDataBinding.homeCvUserCard.setVisibility(View.GONE);
            return;
        }
        viewDataBinding.homeCvUserCard.setVisibility(View.VISIBLE);
        userSelectPopupWindowPopupWindow.setListData(reportList);
    }

    private void getPermissions(){
        //申请定位权限(在onCreate中调用)
        RxPermissions rxPermissions = new RxPermissions(this);
        List<String> permissions = new ArrayList<>();
        permissions.add(Manifest.permission.ACCESS_FINE_LOCATION);
//        if(Build.VERSION.SDK_INT < 33){
//            permissions.add(Manifest.permission.ACCESS_FINE_LOCATION);
//        }
//        permissions.add(Manifest.permission.POST_NOTIFICATIONS);
//        permissions.add(Manifest.permission.READ_MEDIA_IMAGES);
//        permissions.add(Manifest.permission.NEARBY_WIFI_DEVICES);
        String[] arr = new String[]{};
        rxPermissions.request(permissions.toArray(arr))
                .subscribe(new Observer<Boolean>() {
                    Disposable disposable;
                    @Override
                    public void onSubscribe(Disposable d) {
                        disposable = d;
                    }

                    @Override
                    public void onNext(Boolean aBoolean) {

                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        disposable.dispose();
                    }

                    @Override
                    public void onComplete() {
                        disposable.dispose();
                    }
                });
    }

    private void createWebView(String url){
        if (null == agentWeb) {
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT);
            layoutParams.setMargins(0, SizeUtils.dp2px(5), 0, 0);
            layoutParams.height = SizeUtils.dp2px(ReportTypeEnum.REPORT_SLEEP.getDpHeight());

            agentWeb = AgentWeb.with(this)
                    .setAgentWebParent(viewDataBinding.homeLlReportWeb, layoutParams)
                    .closeIndicator()
                    .setWebChromeClient(getWebChromeClient()) //WebChromeClient
                    .setWebViewClient(getWebViewClient())
                    .setSecurityType(AgentWeb.SecurityType.STRICT_CHECK)  ////严格模式 Android 4.2.2 以下会放弃注入对象 ，使用AgentWebView没影响。
                    .setMainFrameErrorView(R.layout.base_layout_empty, -1) //参数1是错误显示的布局，参数2点击刷新控件ID -1表示点击整个布局都刷新， AgentWeb 3.0.0 加入。
                    .addJavascriptInterface("regcallBack", new HomeJSInterface())
                    .createAgentWeb()   //创建AgentWeb。
                    .ready()    //设置 WebSettings。
                    .go(url);

            agentWeb.getWebCreator()
                    .getWebView()
                    .setLayerType(View.LAYER_TYPE_HARDWARE,null);  //开启硬件加速

            WebSettings webSettings = agentWeb.getAgentWebSettings().getWebSettings();
            webSettings.setBlockNetworkImage(false);    //是否阻塞加载网络图片  协议http or https
            webSettings.setAllowFileAccess(true); //允许加载本地文件html  file协议
            webSettings.setJavaScriptEnabled(true);
            agentWeb.getWebCreator().getWebView().setHorizontalScrollBarEnabled(false);//水平不显示
            agentWeb.getWebCreator().getWebView().setVerticalScrollBarEnabled(false); //垂直不显示

            if (BuildConfig.DEBUG) {
                AgentWebConfig.debug();
            }
        }
    }

    private WebChromeClient getWebChromeClient(){
        if (null == webChromeClient) {
            webChromeClient = new WebChromeClient() {
                @Override
                public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
                    LogUtils.d("JS onConsoleMessage()",
                            "Line: " + consoleMessage.lineNumber(),
                            "Message: " + consoleMessage.message());
                    return super.onConsoleMessage(consoleMessage);
                }
            };
        }
        return webChromeClient;
    }

    private WebViewClient getWebViewClient(){
        if (null == webViewClient) {
            webViewClient = new WebViewClient() {
                @Override
                public void onPageFinished(WebView view, String url) {
                    super.onPageFinished(view, url);

                    isWebViewPagerLoadFinished = true;
                    rendererWebViewData();
                    LogUtils.d("onPageFinished()");
                }
            };
        }
        return webViewClient;
    }


    private void agentWebOnResume(){
        if (null == agentWeb) { return; }
        agentWeb.getWebLifeCycle().onResume();
    }

    private void agentWebOnPause(){
        if (null == agentWeb) { return; }
        agentWeb.getWebLifeCycle().onPause();
    }

    private void agentWebOnDestroy(){
        if (null == agentWeb) { return; }
        agentWeb.getWebLifeCycle().onDestroy();
    }

    /** 安卓调用Js */
    private void callWebViewJs(String method, String json){
        if (null == agentWeb) { return; }
        LogUtils.d("JavascriptInterface", "callWebViewJs()", method, json);
        agentWeb.getJsAccessEntrace().quickCallJs(method, json);
    }

    /** 改变网页高度 */
    private void reSizeAgentWebViewHeight(int pxHeight){
        getActivity().runOnUiThread(()-> {
            if (null == agentWeb) { return; }
            ViewGroup.LayoutParams layoutParams =
                    agentWeb.getWebCreator().getWebParentLayout().getLayoutParams();
            layoutParams.height = pxHeight;
            agentWeb.getWebCreator().getWebParentLayout().setLayoutParams(layoutParams);
        });
    }

    /**
     * 开始渲染WebView数据
     */
    private void rendererWebViewData(){
        if (ObjectUtils.isEmpty(webViewReportDada) && isWebViewDataLoadFinished && isWebViewPagerLoadFinished) {
            return;
        }

        callWebViewJs("retEncryptHome", JsonUtil.toJson(webViewReportDada));
    }

    private WardReportBean getWardReportBean(){
        if (ObjectUtils.isEmpty(reportList)) {
            return null;
        }

        String encrypt = webViewReportDada.getEncrypt();

        for (WardReportBean wardReportBean : reportList) {
            if (wardReportBean.getEncrypt().equals(encrypt)) {
                return wardReportBean;
            }
        }

        return null;
    }

    private void toReportMorePager(String reportType){
        if (TextUtils.isEmpty(reportType)) {
            LogUtils.d("reportType is null");
            return;
        }

        WardReportBean wardReportBean = getWardReportBean();
        if (null == wardReportBean) {
            LogUtils.d("wardReportBean is null");
            return;
        }

        String url = "";
        if (reportType.contains("Sleep")) {
            //睡眠报告
            url = wardReportBean.getSleepUrl();
        } else {
            //ADL报告
            url = wardReportBean.getAdlurl();
        }

        Intent intent = new Intent(HomeFragment.this.getActivity(), WebActivity.class);
        intent.putExtra(WebActivity.URL, url);
        intent.putExtra(WebActivity.REPORT_KEY, wardReportBean.getEncrypt());
        HomeFragment.this.getActivity().startActivity(intent);
    }

    @Override
    public void onResume() {
        super.onResume();

        agentWebOnResume();
        setImmersionBar(isImmersionBarTransparent);
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    public void setImmersionBar(boolean isImmersionBarTransparent) {
        if (isImmersionBarTransparent) {
            ImmersionBar.with(this)
                    .statusBarColor(R.color.common_but_blue)
                    .fitsSystemWindows(true)
                    .statusBarDarkFont(true)
                    .autoDarkModeEnable(true).init();


        } else {
            ImmersionBar.with(this)
                    .statusBarColor(android.R.color.white)
                    .fitsSystemWindows(true)
                    .statusBarDarkFont(true)
                    .autoDarkModeEnable(true).init();
        }
    }


    @Override
    public int getLayoutId() {
        return R.layout.home_fragment_main;
    }

    @Override
    public int getBindingVariable() {
        return 0;
    }

    @Override
    protected HomeViewModel getViewModel() {
        BaseViewModelFactroy<HomeBean> myViewModelFactroy = new BaseViewModelFactroy<>(this, this);
        return new ViewModelProvider(this, myViewModelFactroy).get(HomeViewModel.class);
    }

    @Override
    protected void onRetryBtnClick() {
        showLoading();
        viewModel.onLoad();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        agentWebOnDestroy();
        dismissSelectPopupWindow();

    }

    @Override
    public void loadDataSuccess(HomeBean homeBean) {
        isLoad = true;
        //viewDataBinding.homeBannerTop.refreshData(homeBean.getBannerList());
        //viewDataBinding.homeBannerReport.refreshData(homeBean.getReportList());

        alertMultiAdapter.setList(homeBean.getHistroyList());
        earlyMultiAdapter.setList(homeBean.getEarlyWarningLogList());
        viewDataBinding.homeRefreshLayout.finishRefresh(true);
        viewDataBinding.setData(homeBean);
        reportList = homeBean.getReportList();
        updateSelectPopupWindowListData(homeBean.getReportInfoList());
        viewDataBinding.executePendingBindings();
    }

    @Override
    public void loadDataFail(String decs) {
        isLoad = false;
        viewDataBinding.homeRefreshLayout.finishRefresh(false);
    }

    @Override
    public void loginStatusChanged() {
        if(isCreatView){
            getViewModel().isRefresh = false;
            onRetryBtnClick();
        }
    }

    /**
     * JS调用安卓接口
     */
    public class HomeJSInterface {

        /** Js加载完毕后调用安卓，下一步传输数据给Js */
        @SuppressLint("JavascriptInterface")
        @JavascriptInterface
        public void ready(){
            LogUtils.d("JavascriptInterface", "ready()");
            //rendererWebViewData();
        }

        /** Js调试消息打印 */
        @SuppressLint("JavascriptInterface")
        @JavascriptInterface
        public void printLog(String msg){
            LogUtils.d("JavascriptInterface", "printLog()", msg);
        }

        /**
         * 报告切换时，改变卡片高度
         * Sleep：睡眠报告
         * ADL：ADL报告
         * @param type
         */
        @SuppressLint("JavascriptInterface")
        @JavascriptInterface
        public void reportChange(String type){
            LogUtils.d("JavascriptInterface", "reportChange()", type);
            if (TextUtils.isEmpty(type)) {
                return;
            }
            ReportTypeEnum typeEnum = ReportTypeEnum.getReport(type);
            if (null == typeEnum) {
                return;
            }
            reSizeAgentWebViewHeight(SizeUtils.dp2px(typeEnum.getDpHeight()));
        }

        /**
         * 点击报告的More按钮，进入报告详情页面页面
         */
        @SuppressLint("JavascriptInterface")
        @JavascriptInterface
        public void toReportMore(String reportType){
            LogUtils.d("JavascriptInterface", "toReportMore()", reportType);
            toReportMorePager(reportType);
        }

    }
}
